module MEM_WB (
    input wire clk,
    input wire rst_n,
    input wire pause,
    input wire flush,

    input wire rf_we_i,
    input wire [4:0] wR_i,
    input wire [1:0] wd_sel_i,
    input wire [31:0] pc4_i,
    input wire [31:0] ext_i,
    input wire [31:0] alu_c_i,
    input wire [31:0] rd_i,

    output reg rf_we_o,
    output reg [4:0] wR_o,
    output reg [31:0] wD_o,

    input      [31:0] debug_pc_i,
    output reg [31:0] debug_pc_o,
    input             debug_have_inst_i,
    output reg        debug_have_inst_o
);

always @ (posedge clk or negedge rst_n) begin
    if(!rst_n)  debug_pc_o <= 32'b0;
    else        debug_pc_o <= debug_pc_i;
end

always @ (posedge clk or negedge rst_n) begin
    if(!rst_n)  debug_have_inst_o <= 1'b0;
    else        debug_have_inst_o <= debug_have_inst_i;
end

reg [31:0] wD_tmp;
always @(*) begin
    case (wd_sel_i)
        `WD_ALU: wD_tmp = alu_c_i;
        `WD_PC4: wD_tmp = pc4_i;
        `WD_EXT: wD_tmp = ext_i;
        `WD_RD : wD_tmp = rd_i;
        default: wD_tmp = 32'b0;
    endcase
end

always @(posedge clk or negedge rst_n) begin
    if(!rst_n)      wD_o <= 32'b0;
    else if(flush)  wD_o <= 32'b0;
    else if(pause)  wD_o <= wD_o;
    else            wD_o <= wD_tmp;
end

always @(posedge clk or negedge rst_n) begin
    if(!rst_n)      rf_we_o <= 1'b0;
    else if(flush)  rf_we_o <= 1'b0;
    else if(pause)  rf_we_o <= rf_we_o;
    else            rf_we_o <= rf_we_i;
end

always @(posedge clk or negedge rst_n) begin
    if(!rst_n)      wR_o <= 5'b0;
    else if(flush)  wR_o <= 5'b0;
    else if(pause)  wR_o <= wR_o;
    else            wR_o <= wR_i;
end

endmodule